package array;

import java.lang.annotation.Target;
import java.sql.Array;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: leecode
 * @description: 1. 两数之和
 * @author: gh
 * @create: 2020/03/11
 */
public class lee1 {
    /*复杂度分析：
    时间复杂度：O(n^2)
    空间复杂度：O(1)  */
    public static int[] twoSum(int[] nums, int target) {
        int[] rtn = {0, 0};
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    rtn[0] = i;
                    rtn[1] = j;
                    break;
                }
            }
        }
        return rtn;
    }

//    public int[] twoSum(int[] nums, int target) {
//        for (int i = 0; i < nums.length; i++) {
//            for (int j = i + 1; j < nums.length; j++) {
//                if (nums[j] == target - nums[i]) {
//                    return new int[] { i, j };
//                }
//            }
//        }
//        throw new IllegalArgumentException("No two sum solution");
//    }
//
//    作者：LeetCode
//    链接：https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-2/
//    来源：力扣（LeetCode）
//    著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。

    public static int[] twoSum2(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int comp = target - nums[i];
            if (map.containsKey(comp)) {
                return new int[]{map.get(comp), i};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("exce");
    }

    public static void main(String[] args) {
        int[] param = {2, 7, 11, 15};
        System.out.println(Arrays.toString(twoSum(param, 9)));
        System.out.println(Arrays.toString(twoSum2(param, 9)));
    }
}
